﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using ERMSys.Framework.ObjectContextManagement;
using Se7en.Admin.Model;
using Se7en.Admin.Business;
using System.Web;
using System.Web.Security;


namespace Se7en.Admin.Common
{
    public abstract class PageBase : Page
    {
        #region Fields

        ContextManagement<AdminContext> context = new ContextManagement<AdminContext>();

        #endregion

        #region Properties

        protected virtual bool NeedAuthenticate
        {
            get
            {
                return true;
            }
        }

        public bool IsRefresh
        {
            get
            {
                int version = int.TryParse(this.Request[Keys.Session.IsRefresh], out version) ? version : -1;
                return version < ((int?)this.Session[Keys.Session.IsRefresh] ?? 0);
            }
        }

        public AdminContext DBContext
        {
            get
            {
                return context.OC;
            }
        }

        public override System.Web.SessionState.HttpSessionState Session
        {
            get
            {
                return HttpContext.Current.Session;
            }
        }

        public Modes Mode
        {
            get
            {
                if (ViewState[Keys.ViewState.Mode] == null)
                    ViewState[Keys.ViewState.Mode] = Modes.View;

                return (Modes)ViewState[Keys.ViewState.Mode];
            }

            set
            {
                ViewState[Keys.ViewState.Mode] = value;
            }
        }

        protected abstract string LoginUrl { get; }

        protected abstract string BadRequestUrl { get; }

        #endregion

        #region GUI Methods

        protected abstract bool Authenticate();

        protected sealed override void OnPreRender(EventArgs e)
        {
            int version = int.TryParse(this.Request[Keys.Session.IsRefresh], out version) ? version : 0;
            version = version == int.MaxValue ? 0 : version + 1;
            ScriptManager.RegisterHiddenField(this, Keys.Session.IsRefresh, version.ToString());
            this.Session[Keys.Session.IsRefresh] = version;
            base.OnPreRender(e);
        }

        protected override void OnInitComplete(EventArgs e)
        {
            base.OnInitComplete(e);
            if (NeedAuthenticate && (this.Session.IsNewSession || this.Session == null || Session[Keys.Session.UserLogin] == null))
            {
                RedirectToLoginPage();
            }
            if (NeedAuthenticate && !Authenticate())
            {
                BadRequest();
            }
        }

        public PageBase()
        {
            this.Error += new EventHandler(PageBase_Error);
        }

        void PageBase_Error(object sender, EventArgs e)
        {
            //Label lbl = new Label(){ ForeColor = System.Drawing.Color.Red, Text= Server.GetLastError().InnerException.Message};
            //this.Controls.Add(lbl);
            //Server.ClearError();
        }

        #endregion

        #region Methods

        public void ShowMsg(Label lbl, MessageType msgType)
        {
            if (msgType == MessageType.Warning)
                lbl.ForeColor = Color.Red;
            else
                lbl.ForeColor = Color.Blue;
        }

        public void ShowMsg(string message, Label lbl, MessageType msgType)
        {
            lbl.Text = message;
            ShowMsg(lbl, msgType);
        }

        public void BadRequest()
        {   
            Response.Redirect(Page.ResolveUrl(BadRequestUrl),true);
        }

        public void SignOut()
        {
            if (Session != null)
                Session.Abandon();
            FormsAuthentication.SignOut();
            RedirectToLoginPage();

        }

        public void RedirectToLoginPage()
        {
            string path = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath + (HttpContext.Current.Request.QueryString.Count > 0 ? "?" + HttpContext.Current.Request.QueryString : "");
            Response.Redirect(Page.ResolveUrl(LoginUrl) + string.Format("?ReturnUrl={0}", HttpContext.Current.Server.UrlEncode(path)));
        }

        public void ValidateMaxLengthMultiline(TextBox txt)
        {
            txt.Attributes.Add("onkeyup", string.Format("return ValidateLimitCharByControlName('{0}','{1}');", txt.ClientID, txt.MaxLength));
            txt.Attributes.Add("onkeydown", string.Format("return ValidateLimitCharByControlName('{0}','{1}');", txt.ClientID, txt.MaxLength));
            txt.Attributes.Add("onchange", string.Format("return ValidateLimitCharByControlName('{0}','{1}');", txt.ClientID, txt.MaxLength));
        }

        #endregion
    }
}
